<?php

namespace App\Http\Controllers\Api;

use App\Http\Requests\Api\UpdateUserRequest;
use App\Http\Requests\Api\UserRequest;
use App\Http\Resources\UserResource;
use App\Models\Image;
use App\Models\User;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

class UsersController extends Controller {
    //用户注册
    public function store(UserRequest $request){
        $cacheKey = 'vc_'.$request->verification_key;
        $verifyData = Cache::get($cacheKey);
        //dd($verifyData);
        if(!$verifyData) abort(403,'验证码已失效');

        if(!hash_equals($verifyData['code'],$request->verification_code)){
            //401
            throw new AuthenticationException('验证码错误');
        }

        $user = User::create([
            'name'=>$request->name,
            'phone'=>$verifyData['phone'],
            'password'=>$request->password
        ]);

        Cache::forget($cacheKey);

        return (new UserResource($user))->showProtectedFields();


    }

    //获取某个用户的信息
    public function show(Request $request,User $user){
        return new UserResource($user);
    }

    //获取用户自己的信息
    public function me(Request $request){
        return (new UserResource($request->user()))->showProtectedFields();
    }
    //用户编辑
    public function update(UpdateUserRequest $request){
        $user = $request->user();
        $attributes = $request->only(['name','introduction']);
        if($request->avatar_image_id){
            $image = Image::find($request->avatar_image_id);
            $attributes['avatar'] = $image->path;
        }
        $user->update($attributes);
        return (new UserResource($user))->showProtectedFields();
    }
    //获取活跃用户列表
    public function activedUsers(User $user){
        UserResource::wrap('data');
        return UserResource::collection($user->getActiveUsers());
    }

    public function weappStore(UserRequest $request){
        $cacheKey = 'vc_'.$request->verification_key;
        $verifyData = Cache::get($cacheKey);
        if(!$verifyData) abort(403,'验证码已失效');
        if(!hash_equals((string)$verifyData['code'],$request->verification_code)){
            throw new AuthenticationException('验证码错误');
        }
        $data = getWeappData($request->code);
        if(isset($data['errcode'])){
            throw new AuthenticationException('验证码错误');
        }
        $user = User::where('weapp_openid',$data['openid'])->first();

        if($user){
            throw new AuthenticationException('用户已存在，请直接登录');
        }
        $user = User::create([
            'name'=>$request->name,
            'phone'=>$verifyData['phone'],
            'password'=>$request->password,
            'weapp_openid'=>$data['openid'],
            'weixin_session_key'=>$data['session_key']
        ]);
        return (new UserResource($user))->showProtectedFields();
    }

}
